package dapps.web.monitor;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.CRUDActionSupport;

import dapps.entity.monitor.Element;
import dapps.entity.user.Type;
import dapps.service.ServiceException;
import dapps.service.monitor.ElementManager;

@SuppressWarnings("serial")
@Results( { @Result(name = CRUDActionSupport.RELOAD, location = "element.action?page.pageRequest=${page.pageRequest}&tid=${tid}", type = "redirect")})
public class ElementAction extends CRUDActionSupport<Element> {

	@Autowired
	private ElementManager eManager;

	// 基本属性
	private Element entity;
	private Long id;
	private Page<Element> page = new Page<Element>(15);//每页5条记录
	private Long tid;  
	private List<Type> typelist;
	

	// 基本属性访问函数 //

	public Element getModel() {
		return entity;
	}

	@Override
	protected void prepareModel() throws Exception {
		typelist = eManager.getTypelist(new Criterion[]{Restrictions.gt("tid", new Integer(0))},null, new Order[] {Order.asc("tid")});
		if (id != null) {
			entity = eManager.get(id);
		} else {
			entity = new Element();
		}
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Page<Element> getPage() {
		return page;
	}

	// CRUD Action 函数 //

	@Override
	public String list() throws Exception {
		typelist = eManager.getTypelist(new Criterion[]{Restrictions.gt("tid", new Integer(0))},null, new Order[] {Order.asc("tid")});
		if(tid==null||tid<1) tid=2l;
		Criterion[] criterions = {Restrictions.eq("t.id", tid)};
		String[] alias={"type","t"};
		if(StringUtils.isBlank(page.getOrderBy())){
			page.setOrderBy("rank");page.setOrder("asc");
		}		
		page = eManager.findByCriteria(page,null, criterions, alias);
		
		return SUCCESS;
	}

	@Override
	public String input() throws Exception {
		return INPUT;
	}

	@Override
	public String save() throws Exception {
		tid = entity.getType().getId();
		eManager.save(entity);	
		addActionMessage("保存行业指标成功");
		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		try {
			eManager.delete(id);	
			addActionMessage("删除行业指标成功");
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionMessage(e.getMessage());
		}
		return RELOAD;
	}

	public Long getTid() {
		return tid;
	}

	public void setTid(Long tid) {
		this.tid = tid;
	}

	public List<Type> getTypelist() {
		return typelist;
	}

		
}
